<template>
    <div>
        <el-dialog
            v-model="createStore.showAddStaff"
            title="添加员工"
            width="600px"
            :close-on-click-modal="false"
            @close="resetForm"
        >
            <el-form
                ref="formRef"
                :model="form"
                :rules="rules"
                label-width="100px"
                label-position="right"
            >
                <el-form-item label="员工姓名" prop="name">
                    <el-input v-model="form.name" placeholder="请输入员工姓名" />
                </el-form-item>
                
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
                </el-form-item>
                
                <el-form-item label="员工住址" prop="address">
                    <el-input v-model="form.address" placeholder="请输入员工住址" />
                </el-form-item>
                
                <el-form-item label="服务类型" prop="services">
                    <el-select
                        v-model="form.services"
                        multiple
                        placeholder="请选择服务类型"
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in serviceOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="员工等级" prop="rank">
                    <el-select
                        v-model="form.rank"
                        placeholder="请选择员工等级"
                        style="width: 100%"
                    >
                        <el-option label="金牌员工" value="金牌员工"/>
                        <el-option label="银牌员工" value="银牌员工"/>
                        <el-option label="铜牌员工" value="铜牌员工"/>
                        <el-option label="铁牌员工" value="铁牌员工"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="工作周期" prop="workPeriods">
                    <el-select
                        v-model="form.workPeriods"
                        multiple
                        placeholder="请选择工作周期"
                        style="width: 100%"
                    >
                        <el-option label="全天" value="全天" />
                        <el-option label="上午" value="上午" />
                        <el-option label="下午" value="下午" />
                        <el-option label="晚上" value="晚上" />
                    </el-select>
                </el-form-item>
                <el-form-item label="薪水" prop="salary">
                    <el-input v-model="form.salary" placeholder="请输入薪水" type="number" />
                </el-form-item>
                <el-form-item label="接单状态" prop="status">
                    <el-switch
                        v-model="form.status"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="开启接单"
                        inactive-text="暂停接单"
                    />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, defineExpose, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useCreateStore } from '@/stores/useCreateStore'
import instance from '@/api'
import { emitter } from '@/utils/emitter'

const createStore = useCreateStore()
interface ServiceType {
  label: string;
  value: string;
}
const serviceOptions = ref<ServiceType[]>([])

defineOptions({
    name: 'CreateStaff'
})

const formRef = ref<FormInstance>()

const form = reactive({
    name: '',
    phone: '',
    address: '',
    services: [] as string[],
    rank: '',
    workPeriods: [] as string[],
    salary: 0,
    status: 1
})

const isEdit = ref(false)
const editId = ref<number | null>(null)

const openEdit = (staff: any) => {
    isEdit.value = true
    editId.value = staff.id
    Object.assign(form, {
        ...staff,
        services: [...(staff.services || [])],
        workPeriods: [...(staff.workPeriods || [])]
    })
    createStore.showAddStaff = true
}
defineExpose({ openEdit })

const rules = reactive<FormRules>({
    name: [
        { required: true, message: '请输入员工姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '请输入员工住址', trigger: 'blur' }
    ],
    services: [
        { required: true, message: '请选择服务类型', trigger: 'change' },
        { type: 'array', min: 1, message: '请至少选择一项服务类型', trigger: 'change' }
    ],
    rank: [
        { required: true, message: '请选择员工等级', trigger: 'change' }
    ],
    workPeriods: [
        { required: true, message: '请选择工作周期', trigger: 'change' },
        { type: 'array', min: 1, message: '请至少选择一项工作周期', trigger: 'change' }
    ],
    salary: [
        { required: true, message: '请输入薪水', trigger: 'blur' }
    ]
})

const submitForm = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                let resp
                if (isEdit.value && editId.value) {
                    resp = await instance.put(`/api/staff/updateStaff/${editId.value}`, form)
                } else {
                    resp = await instance.post('/api/staff/addStaff', form)
                }
                if (resp.data) {
                    createStore.showAddStaff = false
                    if (isEdit.value) {
                        window.dispatchEvent(new CustomEvent('edit-success', { detail: resp.data }))
                    } else {
                        emitter.emit('staff-added', resp.data)
                    }
                    ElMessage.success(isEdit.value ? '修改员工成功' : '添加员工成功')
                    formRef.value?.resetFields()
                    isEdit.value = false
                    editId.value = null
                }
            } catch (error) {
                ElMessage.error(isEdit.value ? '修改员工失败' : '添加员工失败')
            }
        } else {
            ElMessage.error('请完善表单信息')
        }
    })
}
const resetForm = () => {
    formRef.value?.resetFields()
    isEdit.value = false
    editId.value = null
    // 手动重置表单数据
    Object.assign(form, {
        name: '',
        phone: '',
        address: '',
        services: [],
        rank: '',
        workPeriods: [],
        salary: 0,
        status: 1
    })
}

const handleCancel = () => {
    createStore.showAddStaff = false
    resetForm()
}

onMounted(async () => {
    const resp = await instance.get('/api/serviceType/lists')
    const { status, data } = resp
    if(status === 200) {
        serviceOptions.value = data.map((item: { id: number; service_type: string }) => ({
            value: item.service_type,
            label: item.service_type
        }))
    }
})
</script>

<style scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>